package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.RequestAndResultCode;
import com.bjesc_b2c.app.appraiset.adapter.CarfromOneAdapter;
import com.bjesc_b2c.app.appraiset.adapter.DrownSeriesAdapter;
import com.bjesc_b2c.app.appraiset.adapter.ListDropDownAdapter;
import com.bjesc_b2c.app.appraiset.adapter.PriceAdapter;
import com.bjesc_b2c.app.appraiset.adapter.UploadHistoryAdapter;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.http.IApiFragmentRequest;
import com.bjesc_b2c.app.appraiset.mvp.presenter.GetCarForPresenter;
import com.bjesc_b2c.app.appraiset.utils.DataUtils;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.AdjustmentPop;
import com.bjesc_b2c.app.appraiset.widget.view.IndexView;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.widget.SpringView;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.util.CustomSharedPreferences;
import com.rxretrofit_build.util.MapUtil;
import com.yyydjk.library.DropDownMenu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import app.pinggushi.bjesc.com.baserecyclerview.adapter.CommonAdapter;
import app.pinggushi.bjesc.com.baserecyclerview.adapter.MultiItemTypeAdapter;
import app.pinggushi.bjesc.com.baserecyclerview.adapter.wrapper.HeaderAndFooterWrapper;
import butterknife.Bind;
import butterknife.OnClick;
import master_bean.CarForBean;
import master_bean.CarSeriesModelBean;
import master_bean.SourceFindBean;
import master_bean.ToDayBean;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

/**
 * Created by yidong on 2017/8/14.
 */

public class DealerUploadCar extends BaseActivity implements SpringView.OnFreshListener,
        MultiItemTypeAdapter.OnItemClickListener, UploadHistoryAdapter.statusListener, IndexView.OnSetIndexListenre,
        AdjustmentPop.AdjustmencallBack {

    private View lin_pop;
    private AdjustmentPop pop;
    private UploadHistoryAdapter mdapter;
    private List<ToDayBean> historydata = new ArrayList<ToDayBean>();
    private GetCarForPresenter carForPresenter;
    private int findType = 0;
    private int page = 1;
    private boolean isLodmore = true;
    private String fBrandId = "";
    private List<CarForBean> dealerList;
    private ListDropDownAdapter statusAdapter;
    private String headers[] = {"品牌", "价格", "状态"};
    private List<CarForBean> brandList;
    private List<CarForBean> statusList;
    private List<CarForBean> priceList;
    private View brandView;
    private View priceView;
    private View dealerView;
    private List<View> popupViews = new ArrayList<>();
    private LinearLayoutManager brandManager;
    private LinearLayoutManager dealerManager;
    private DrownSeriesAdapter serAdapter;
    private PriceAdapter priceAdapter;
    private CarfromOneAdapter brandAdapter;
    private CarfromOneAdapter dealerAdapter;
    private CarfromOneAdapter dealerNameAdapter;
    private EditText priceStartEdit;
    private EditText priceEndEdit;
    private TextView sureTV;
    private HeaderAndFooterWrapper headerAndFooterWrapper;
    private RecyclerView recyclerView;
    private SpringView springView;
    private RecyclerView brandRecycler;
    private RecyclerView dealerRecycler;
    private RecyclerView seriesRecycler;
    private RecyclerView pricereRecycler;
    private IndexView indexView;
    private IndexView dealerindexView;
    private SourceFindBean findBean;
    private String price_start;
    private String price_end;
    private String deralerID;

    @Bind(R.id.dropDownMenu)
    DropDownMenu mDropDownMenu;
    @Bind(R.id.edit_search_id)
    EditText edit_search_id;
    @Bind(R.id.iv_return)
    LinearLayout returnLin;
    @Bind(R.id.tv_title)
    TextView titleTv;

    @Override
    protected int getLayout() {
        return R.layout.fragment_source_edit;
    }

    @Override
    protected void initEventAndData() {
        returnLin.setVisibility(View.VISIBLE);
        titleTv.setText(getIntent().getStringExtra("Title"));
        deralerID = getIntent().getStringExtra("carFofId");
        initViews();
    }

    @Override
    protected void createPresenter() {
//        carForPresenter = new GetCarForPresenterImpl(this, this);
        switchTypeLoaded();
    }

    private void initViews() {
        findBean = new SourceFindBean();
        brandManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        brandList = DataUtils.getCarForBean(this);//初始化品牌数据
        statusList = DataUtils.getCarStatus(this);
        priceList = DataUtils.getPriceList(this);
        shortList();
        ListView statusView = new ListView(this);
        statusView.setDividerHeight(0);
        statusAdapter = new ListDropDownAdapter(this, statusList);
        statusView.setAdapter(statusAdapter);
        brandView = getLayoutInflater().inflate(R.layout.layout_pop_car_brand, null);
        dealerView = getLayoutInflater().inflate(R.layout.layout_pop_car_brand, null);
        dealerindexView = (IndexView) dealerView.findViewById(R.id.index_view);
        dealerindexView.setVisibility(View.GONE);
        priceView = getLayoutInflater().inflate(R.layout.layout_price_view, null);
        brandRecycler = (RecyclerView) brandView.findViewById(R.id.recycler_view);
        dealerRecycler = (RecyclerView) dealerView.findViewById(R.id.recycler_view);
        dealerManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        dealerRecycler.setLayoutManager(dealerManager);
        pricereRecycler = (RecyclerView) priceView.findViewById(R.id.price_recycler);
        priceAdapter = new PriceAdapter(this, R.layout.layout_item_select_car_brand, priceList);
        initHeader(priceAdapter);
        pricereRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        pricereRecycler.setAdapter(headerAndFooterWrapper);
        priceAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                mDropDownMenu.setTabText(position == 1 ? headers[1] : priceList.get(position - 1).getName());
                findType = 3;
                page = 1;
                price_start = priceList.get(position - 1).getPrice_start();
                price_end = priceList.get(position - 1).getPrice_end();
                switchTypeLoaded();
                mDropDownMenu.closeMenu();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        seriesRecycler = (RecyclerView) brandView.findViewById(R.id.recycler_view_series);
        brandAdapter = new CarfromOneAdapter(this, R.layout.layout_item_select_car_brand, brandList, 1);
        brandRecycler.setLayoutManager(brandManager);
        brandRecycler.setAdapter(brandAdapter);
        brandAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                seriesRecycler.setVisibility(View.GONE);
                if (position == 0) {
                    findType = 2;
                    page = 1;
                    fBrandId = "";
                    switchTypeLoaded();
                    mDropDownMenu.setTabText(position == 0 ? headers[0] : brandList.get(position).getName());
                    mDropDownMenu.closeMenu();
                } else {
                    getCarSeries(brandList.get(position).getId());
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        indexView = (IndexView) brandView.findViewById(R.id.index_view);
        indexView.setOnSetIndexListenre(this);
        brandRecycler.setOnScrollListener(scrollListener);
//        popupViews.add(dealerView);
        popupViews.add(brandView);
        popupViews.add(priceView);
        popupViews.add(statusView);
        statusView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                statusAdapter.setCheckItem(position);
                mDropDownMenu.setTabText(position == 0 ? headers[2] : statusList.get(position).getName());
                findType = 4;
                page = 1;
                fBrandId = statusList.get(position).getId();
                switchTypeLoaded();
                mDropDownMenu.closeMenu();
            }
        });
        View contentView = getLayoutInflater().inflate(R.layout.layout_dropdown_view, null);
        springView = (SpringView) contentView.findViewById(R.id.spring_view);
        recyclerView = (RecyclerView) contentView.findViewById(R.id.recycler_view);
        springView.setListener(this);
        springView.setHeader(new DefaultFooter(this));
        springView.setFooter(new DefaultFooter(this));
        springView.setType(SpringView.Type.FOLLOW);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mDropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);

        edit_search_id.setOnKeyListener(new View.OnKeyListener() {

            @Override

            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    if (edit_search_id.getText().toString().length() > 4) {
                        SourceFindBean findBean1 = new SourceFindBean();
                        findBean1.setCar_id(edit_search_id.getText().toString());
                        findBean1.setPage(0);
                        getHistoryData(findBean1);
                    } else {
                        showToast("车源ID位数不对");
                    }
                }
                return false;
            }
        });

    }

    private RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int position = brandManager.findFirstVisibleItemPosition();
            indexView.refresh(brandList.get(position + 1).getFirstLetter().charAt(0));
        }
    };

    private void initHeader(CommonAdapter mAdapter) {
        headerAndFooterWrapper = new HeaderAndFooterWrapper(mAdapter);
        View priceHeader = getLayoutInflater().inflate(R.layout.layout_price_header, null);
        priceStartEdit = (EditText) priceHeader.findViewById(R.id.ed_price_start);
        priceEndEdit = (EditText) priceHeader.findViewById(R.id.ed_price_end);
        sureTV = (TextView) priceHeader.findViewById(R.id.tv_sure);
        sureTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                price_start = priceStartEdit.getText().toString();
                price_end = priceEndEdit.getText().toString();
                findType = 3;
                page = 1;
                switchTypeLoaded();
                mDropDownMenu.closeMenu();
            }
        });
        priceStartEdit.addTextChangedListener(textWatcher);
        priceEndEdit.addTextChangedListener(textWatcher);
        headerAndFooterWrapper.addHeaderView(priceHeader);
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            if (priceStartEdit.getText().length() > 0 || priceEndEdit.getText().length() > 0) {
                sureTV.setBackgroundColor(getResources().getColor(R.color.colorFFF95852));
            } else {
                sureTV.setBackgroundColor(getResources().getColor(R.color.colorFFD8D8D8));
            }
        }
    };

    private void refreshData(List<ToDayBean> data) {
        if (page == 1) {
            historydata.clear();
        }
        Logger.d("findType====" + findType);
        Logger.d("fBrandId====" + fBrandId);
        Logger.d("fBrandId====" + fBrandId);
        historydata.addAll(data);
        Logger.d("page====" + page);
        if (mdapter == null) {
            mdapter = new UploadHistoryAdapter(this, R.layout.layout_item_source_edit, historydata);
            mdapter.setOnItemClickListener(this);
            mdapter.setSListener(this);
            recyclerView.setAdapter(mdapter);
        } else {
            mdapter.refresh(historydata);
        }
    }

    /**
     * @param view
     * @param holder
     * @param position
     */
    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        CustomSharedPreferences.saveString(this, new MapUtil().put(KeyBean.CARID.valueOf(), historydata.get(position).getCar_id()).build(), KeyBean.FILE_NAME.valueOf());
        startIntent(new Intent(DealerUploadCar.this, CarDetailsActivity.class), false);
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }

    @OnClick({R.id.tv_title, R.id.iv_return})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
                if (edit_search_id.getText().toString().length() > 4) {
                    SourceFindBean findBean1 = new SourceFindBean();
                    findBean1.setCar_id(edit_search_id.getText().toString());
                    findBean1.setPage(0);
                    getHistoryData(findBean1);
                } else {
                    showToast("车源ID不正确！");
                }
                break;
            case R.id.iv_return:
                finish();
                break;
        }
    }

    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        page = 1;
        Logger.e("onRefresh  =brandId=" + fBrandId + "findType==" + findType + "page==" + page);
        Logger.d("page==" + page);
        switchTypeLoaded();
    }

    /**
     * 上拉加载
     */
    @Override
    public void onLoadmore() {
        if (isLodmore) {
            page++;
            switchTypeLoaded();
        } else {
            springView.onFinishFreshAndLoad();
        }
        Logger.e("onLoadmore  =brandId=" + fBrandId + "findType==" + findType + "page==" + page);

    }

    private void switchTypeLoaded() {
        findBean.setPage(page);
        switch (findType) {
            case 0:
                price_start = "";
                price_end = "";
                findBean = new SourceFindBean();
                break;
            case 1:
                findBean.setDealer_id(fBrandId);
                break;
            case 2:
                findBean.setCarserie_id(fBrandId);
                break;
            case 3:
                findBean.setPrice_start(price_start);
                findBean.setPrice_end(price_end);
                break;
            case 4:
                findBean.setStatus(fBrandId);
                break;
            case 5:
                findBean.setMarket_id(fBrandId);
                break;
        }
        getHistoryData(findBean);
    }

    @Override
    public void adjustment(int position) {//调价
        String carid = mdapter.getDatas().get(position).getCar_id();
        pop = new AdjustmentPop(this, carid, this);
//      pop.setFocusable(false);
        pop.showAtLocation(pop.getContentView(), Gravity.TOP, 0, 0);
    }

    @Override
    public void adjustmenSuccess(CarSeriesModelBean cbean) {//调价成功回调
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
        }
        showToast("调价成功！");
        page = 1;
        findType = 0;
        switchTypeLoaded();
    }

    public void offShelf(int position ) {
        Intent intent = new Intent(DealerUploadCar.this, CarOffShelfActivity.class);
        intent.putExtra("Car_id", mdapter.getDatas().get(position).getCar_id());
        Logger.d("Car_id===== " + mdapter.getDatas().get(position).getCar_id());
        startActivityForResult(intent, RequestAndResultCode.SelectCarBrandActivity_ResultCode);
    }

    private void getHistoryData(SourceFindBean findBean) {
        HashMap<String, Object> map = new MapUtil().
                put("dealer_id", deralerID).
                put("brand_id", findBean.getBrand_id()).
                put("market_id", findBean.getMarket_id()).
                put("status", findBean.getStatus()).
                put("car_id", findBean.getCar_id()).//车源id
                put("carserie_id", findBean.getCarserie_id()).//车系
                put("price_start", findBean.getPrice_start()).
                put("price_end", findBean.getPrice_end()).
                put("page", page).build();

        RxRequest.request(ShowType.DISMISS, RxRequest.getClient(DealerUploadCar.this, map).create(IApiFragmentRequest.class).uploadHistory(),
                new BaseSubscriber<TokenBean<List<ToDayBean>>>(DealerUploadCar.this) {
                    @Override
                    public void onSuccess(TokenBean<List<ToDayBean>> o) {
                        if (o.getData() != null && o.getData().size() > 0) {
                            refreshData(o.getData());
                            isLodmore = true;
                        } else {
                            showToast("没有数据！");
                            if (page == 1) {
                                mdapter = null;
                                recyclerView.setAdapter(mdapter);
                            }
                            isLodmore = false;
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        springView.onFinishFreshAndLoad();
                        cancelLoading();
                    }

                    @Override
                    public void onStart() {
                        showLoading();
                    }

                    @Override
                    public void onCompleted() {
                        cancelLoading();
                        springView.onFinishFreshAndLoad();
                    }
                });
    }

    @Override
    public void setIndexListenre(char index) {
        for (int i = 0; i < brandList.size(); i++) {
            if (String.valueOf(index).equals(brandList.get(i).getFirstLetter())) {
                brandManager.scrollToPositionWithOffset(i, 0);
                break;//加了break显示才会更准确—yd
            }
        }
    }
    private void getCarSeries(String brandId) {
        HashMap<String, Object> build = new MapUtil()
                .put("brand_id", brandId)
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(DealerUploadCar.this, build).create(IApiActivityRequest.class).getCarSeries()
                , new BaseSubscriber<TokenBean<List<CarSeriesModelBean>>>(DealerUploadCar.this) {
                    @Override
                    public void onSuccess(TokenBean<List<CarSeriesModelBean>> o) {
                        if (o.getData() != null && o.getData().size() > 0) {
                            initViewSeries(o.getData());
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }

    private void initViewSeries(final List<CarSeriesModelBean> data) {
        seriesRecycler.setVisibility(View.VISIBLE);
        if (serAdapter == null) {
            serAdapter = new DrownSeriesAdapter(DealerUploadCar.this, R.layout.layout_item_dwn_serice, data);
        } else {
            serAdapter.refresh(data);
        }
        seriesRecycler.setLayoutManager(new LinearLayoutManager(DealerUploadCar.this, LinearLayoutManager.VERTICAL, false));
        seriesRecycler.setAdapter(serAdapter);
        serAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                findType = 2;
                page = 1;
                fBrandId = data.get(position).getId();
                switchTypeLoaded();
                mDropDownMenu.setTabText(data.get(position).getName());
                mDropDownMenu.closeMenu();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    private void shortList() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Collections.sort(brandList, new Comparator<CarForBean>() {
                    public int compare(CarForBean carBrandBean1, CarForBean carBrandBean2) {
                        if (carBrandBean1.getFirstLetter().charAt(0) > carBrandBean2.getFirstLetter().charAt(0)) {
                            return 1;
                        }
                        if (carBrandBean1.getFirstLetter().charAt(0) == carBrandBean2.getFirstLetter().charAt(0)) {
                            return 0;
                        }
                        return -1;
                    }
                });
                CarForBean carBean = new CarForBean();
                carBean.setId("0");
                carBean.setName("不限");
                brandList.add(0, carBean);
            }
        });
    }

}


